package com.mandao.concurrency.example.atomic;

import com.mandao.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程安全性:
 *  *   原子性:提供了互斥访问,同一时刻只能有一个线程来对它进行操作
 *  *   可见性:一个线程对主内存的修改可以及时的被其他线程观察到
 *  *   有序性:一个线程观察其他线程中的指令执行顺序,由于指令重排序的存在,该观察结果一般杂乱无序
 *
 *  该测试类使用了 atomicxxx: CAS  unsafe.compareAndSwap*
 * @author 蜗牛
 */
@Slf4j
@ThreadSafe
public class AtomicExample1 {
    //请求总数
    public static int clientTotal = 5000;
    //并发执行的线程
    public static int threadTotal = 200;
    //计数
    public static AtomicInteger count = new AtomicInteger(0);

    public static void main (String[] args) throws InterruptedException {
        //线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //信号量
        final Semaphore semaphore = new Semaphore(threadTotal);
        //计数器
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        //
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(()->{
                try {
                    // 进源码看acquire方法的作用 判断当前线程是否可用
                    semaphore.acquire();
                    add();
                    // 是否当前线程
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.info("exception",e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}",count.get());
    }

    /**
     * 计数的方法
     */
    public static void add(){
        // 先增加 再获取当前值
        count.incrementAndGet();
        // 先获取当前值 再增加操作
        count.getAndIncrement();
    }
}
